﻿#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
using namespace std;
#include<string>
#include<vector>


void test1()
{
	vector<int> v1(5,1);
	vector<int> v2(v1.begin(), v1.end());

	//遍历
	vector<int>::iterator it = v2.begin();
	while (it != v2.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;

	for (auto e : v2)
	{
		cout << e << " ";
	}
	cout << endl;
}

// reserve
void test2()
{
	vector<int> v2;
	v2.push_back(0);
	size_t sz = v2.capacity();
	cout << "capacity:" << sz << endl;
	int i = 0;
	while (i < 100)
	{
		v2.push_back(i);
		if (sz != v2.capacity())
		{
			sz = v2.capacity();
			cout << "reserve:" << sz << endl;
		}
		i++;
	}
}

// resize
void test3()
{
	vector<int> v3(10, 1);
	cout << v3.capacity() << endl;
	v3.resize(15, 2);
	cout << v3.capacity() << endl;
	// resize()不会让v3缩容，但是会改变有效数据个数
	v3.resize(10, 0);
	cout << v3.capacity() << endl;
}

void test4()
{
	vector<int>v4(10,1);
	v4.push_back(0);
	v4.insert(v4.begin() + 5, 2);
}


void test5()
{
	vector<int> v(5, 1);
	vector<vector<int>> vv(10, v);

	for (int i = 0; i < vv.size(); i++)
	{
		for (auto e : vv[i])
		{
			cout << e << " ";
		}
		cout << endl;
	}
}

void test()
{
	//vector<vector<int>> vv(10);
	int numRows = 5;
	vector<vector<int>> v(numRows);
	for (int i = 0; i < numRows; i++)
	{
		v[i].resize(i + 1, 1); //扩容时如果不传第二个参数，默认初始化为0
		//v[i][0] = v[i][i] = 1;
	}
	for (int i = 2; i < numRows; i++)
	{
		for (int j = 1; j < i; j++)
		{
			v[i][j] = v[i - 1][j - 1] + v[i - 1][j];
		}
	}
}

void test6()
{
	vector<int> v;
	v.reserve(5);
	/*std::vector 的 reserve(n) 函数只是预留内存空间，并不会真正构造元素，也不会改变 vector 的大小（size()）。
	此时 vector 中没有任何有效元素，size() 仍为 0。而代码中使用 v[i]去访问和修改下标为 0 到 4 的元素，
	相当于访问了 “不存在的内存区域”，属于越界访问。*/
	for (int i = 0; i < 5; i++)
	{
		v[i] = i + 1;
	}
}
int main()
{
	//test1();
	//test4();
	test6();
	return 0;
}



